package com.cxf.windex.rest;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.cxf.windex.base.msg.ObjectRestResponse;
import com.cxf.windex.base.rest.BaseRestController;
import com.cxf.windex.base.util.EncryptUtil;
import com.cxf.windex.base.util.SmsDemo;
import com.cxf.windex.biz.CxfUserBiz;
import com.cxf.windex.biz.CxfUserInfoBiz;
import com.cxf.windex.entity.CxfUser;
import com.cxf.windex.entity.CxfUserInfo;
import com.cxf.windex.enums.TypeEnums;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.io.IOException;
import java.util.Date;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author chenxf
 * @date 5/10/2018
 * @description
 */
@Api(tags = {"聚能小宝 - 用户信息接口"})
@Controller
@RequestMapping("userInfo")
public class CxfUserInfoController extends
    BaseRestController<CxfUserInfoBiz, CxfUserInfo> {
  @Autowired
  CxfUserBiz cxfUserBiz;


  @Value("${sms.accessKeyId}")
  private String accessKeyId;

  @Value("${sms.accessKeySecret}")
  private String accessKeySecret;

  @Value("${sms.signName}")
  private String signName;

  @Value("${sms.templateCode}")
  private String templateCode;

  @Autowired
  private CacheManager cacheManager;

  private String cacheName="smsCode";

  @ApiOperation(value="获取用户信息", notes="获取当前用户信息")

  @RequestMapping(value = "/getInfo", method = RequestMethod.GET)
  @ResponseBody
  public ObjectRestResponse getInfo(){
    resultMap.put("name",this.getCurrentName());
    resultMap.put("phone",this.getCurrentUserName());
    CxfUserInfo queryEntity=new CxfUserInfo();
    queryEntity.setUserid(this.getCurrentUserId());
    CxfUserInfo entity=baseBiz.selectOne(queryEntity);

    if(entity!=null){
      resultMap.put("realname",entity.getRealname());
      resultMap.put("aliPay",entity.getAlipay());
      resultMap.put("id",entity.getId());
      resultMap.put("alipay",entity.getAlipay());
    }else {
      resultMap.put("realname","");
      resultMap.put("aliPay","");
      resultMap.put("id","");

    }
    return  new ObjectRestResponse().rel(true).msg("查询成功").result(resultMap);
  }

  @ApiOperation(value="保存用户信息", notes="保存当前用户信息")
  @RequestMapping(value = "/save", method = RequestMethod.POST)
  @ResponseBody
  public ObjectRestResponse save(CxfUserInfo userInfo,String code,String name){
    String phone=this.getCurrentUserName();


    if(StringUtils.isNotBlank(userInfo.getRealname())){
      userInfo.setRealnameStatus("1");
      userInfo.setRealnameTimes(new Date());
      userInfo.setPhoneStatus("1");
    }

    if(StringUtils.isNotBlank(userInfo.getAlipay())){
      userInfo.setAlipaystatus("1");
    }

    CxfUser user=new CxfUser();
    user.setId(this.getCurrentUserId());
    if(!this.getCurrentName().equals(name)){
      user.setName(name);
    }

    if(userInfo.getId()==null || userInfo.getId()==0){
      userInfo.setUserid(user.getId());
      baseBiz.insertSelective(userInfo);
      user.setType(TypeEnums.V2.getKey());
    }else{
      baseBiz.updateSelectiveById(userInfo);
    }
    this.updateCurrentUserName(user);
    cxfUserBiz.updateSelectiveById(user);

    return  new ObjectRestResponse().rel(true).msg("保存成功");
  }

  @ApiOperation(value="发送短信验证码", notes="发送短信验证码")
  @RequestMapping(value = "/sendText", method = RequestMethod.GET)
  @ResponseBody
  public ObjectRestResponse sendText(String phone) throws IOException {
    if (StringUtils.isBlank(phone)) {

      return new ObjectRestResponse().rel(false).msg("请输入手机号码");
    }

    if (!validate(phone)) {
      return new ObjectRestResponse().rel(false).msg("一分钟内只能发送一次验证码");
    }
    // 手机验证码改成4位
    String veryCode = RandomStringUtils.randomNumeric(4);

    // 验证码放入缓存
    cacheManager.getCache(cacheName).put(phone ,
        veryCode);
    cacheManager.getCache(cacheName).put(
        phone  + "Date", LocalDateTime.now());
    logger.info("veryCode:" + veryCode);
    // 发送验证码
    try {
      SendSmsResponse response = SmsDemo
          .sendSms(phone,signName, templateCode,veryCode,accessKeyId,accessKeySecret);
      logger.debug("result={}",response.getMessage());
    } catch (ClientException e) {
      logger.error(e.getErrMsg());
    }

    return new ObjectRestResponse().rel(true).msg("发送成功");

  }
  /**
   * 1分钟内 同一手机号 同一应用只发送一次短信验证码
   * @param phone 手机号
   * @return
   */
  private boolean validate(String phone) {

    LocalDateTime  sendTime=
        cacheManager.getCache(cacheName).get(phone  + "Date", LocalDateTime.class);
    if (sendTime != null) {
      if(sendTime.plusSeconds(60).isAfter(LocalDateTime.now())){
        return false;
      }
    }
    return true;

  }
}
